﻿using Bandit.Helpers;
//new
using Bandit.UI;
using Bandit.UI.Controls;
using ETC.HallICElan2In1.Core;
using ETC.HallICElan2In1.Helpers;
using ETC.HallICElan2In1.Models;
using RD.UsbHid;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ETC.HallICElan2In1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : BanditWindow
    {
        /// <summary>
        /// 视图模型
        /// </summary>
        public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

        
        public MainWindow()
        {
            InitializeComponent();

            TestConfig.LoadConfig();

            this.OnReceiveProcessMessage += (sender, msg) =>
            {
                string[] array = msg.Split(',', StringSplitOptions.RemoveEmptyEntries);

                if (array.Length == 2)
                {
                    switch (array[0])
                    {
                        case "AutoSN":
                            this.ViewModel.TestInfo.Barcode = array[1].Trim();
                            StartTest();
                            break;
                        default:
                            break;
                    }
                }
            };

            #region Window Loaded

            this.Loaded += delegate
            {
                ViewModel.OnClick = new Bandit.UI.MVVM.CommandHandler(OnClick);

                this.DataContext = ViewModel;

                this.rtxtTestData.Document.Blocks.Clear();
                //在这里连接USB
                if (ViewModel.Setting.IsUSBCommunication)
                {
                    this.InitUSBDevice();
                    AppendTestData("Hall 当前使用USB通信方式", MyBrushes.PASS);
                }
                else
                {
                    this.InitSerialPort();
                    AppendTestData("Hall 当前使用Serial通信方式", MyBrushes.PASS);
                }

                this.txtBarcode.Focus();

                UpdateStartButtonState();

                #region 初始化Log文件监视

                InitializeLogWathcer();

                LinkSoftware();

                #endregion
            };

            #endregion

            this.Closed += delegate
            {
                if(_Elan_SoftwareProcess != null)
                {
                    _Elan_SoftwareProcess.Kill();
                }
            };

            #region Window KeyDown
            this.KeyDown += (sender, e) =>
            {
                if (e.Key == Key.F5 || e.Key == Key.Enter)
                {
                    this.StartTest();
                }
            };
            #endregion

            this.rtxtTestData.TextChanged += delegate
            {
                try
                {
                    this.ThreadSafe(() =>
                    {
                        this.rtxtTestData.ScrollToEnd();
                    });
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "rtxtTestData.TextChanged", true);
                }
            };
        }

        #region OnClick Event

        private void OnClick(object parameter)
        {
            if (parameter != null)
            {
                switch (parameter.ToString())
                {
                    case "StartTest":
                        {
                            this.StartTest();
                        }
                        break;
                    case "StopTest":
                        {
                            this.StopTest();
                        }
                        break;
                   
                    case "TestConfig":
                        {
                            string password = "";
                            #if !DEBUG
                            password = "TPKETC";
                            #endif

                            if(this.ShowPasswordDialog("Enginess Login", password))
                                ShowWindow<Windows.FrmConfig>(this);
                        }
                        break;
                    case "Setting":
                        {
                            ShowWindow<Windows.FrmSetting>(this);
                        }
                        break;
                    case "CheckUpdate":
                        if (!App.CheckUpdate())
                        {
                            this.ShowDialog(App.GetString("NotNeedUpdatePrompt"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.OK);
                        }
                        break;
                    case "About":
                        {
                            Windows.FrmAbout.Show(this);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        #endregion

        #region 当设备连接或断开后更新开始测试按钮的状态
        private void UpdateStartButtonState()
        {
            ViewModel.TestInfo.EnabledStartButton = ViewModel.Setting.IsUSBCommunication ? USBHelper.Instance.IsConnect : HallSensorHelper.Instance.IsConnected; //RelayBoardHelper.RelayBoards.All(s => s.IsConnect) && this._Meter.IsConnected;

            if (ViewModel.TestInfo.EnabledStartButton)
            {
                ViewModel.HallStatus1.Update("Ready", MyBrushes.RichBlue);
                ViewModel.HallStatus2.Update("Ready", MyBrushes.RichBlue);
                ViewModel.Status.Update("Ready", MyBrushes.RichBlue);
                ViewModel.UsbStatus.Update("Serial Connected", MyBrushes.Green);
            }
            else
            {
                ViewModel.HallStatus1.Update("Waiting", MyBrushes.Red);
                ViewModel.HallStatus2.Update("Waiting", MyBrushes.Red);
                ViewModel.Status.Update("Waiting...", MyBrushes.Red);
                ViewModel.UsbStatus.Update("Serial DisConnect", MyBrushes.Red);
            }
        }
        #endregion

        #region Serial
        #region Serial Autoset

        private AutoResetEvent _HallAutoEvent = new AutoResetEvent(false);
        private void HallSet()
        {
            this._HallAutoEvent.Set();
        }

        private void HallWait(int seconds)
        {
            this._HallAutoEvent.Reset();
            this._HallAutoEvent.WaitOne(TimeSpan.FromSeconds(seconds));
        }

        #endregion

        private void InitSerialPort()
        {
            HallSensorHelper.Reset();

            Thread.Sleep(100);

            HallSensorHelper.Instance.OnConnectedChanged += Instance_OnConnectedChanged;

            HallSensorHelper.Instance.OnError += (sender, e) =>
            {
                LogHelper.Error(e.Exception, e.Title);
            };

            HallSensorHelper.Instance.OnReceivedChanged += Instance_OnReceivedChanged;

            HallSensorHelper.Instance.Connect("\r\n", 115200, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "");
        }

        private void Instance_OnReceivedChanged(DeviceBase sender, OnReceivedArgs e)
        {
            string[] data = e.HexData;

            if (ViewModel.TestInfo.IsTesting)
            {
                LogHelper.Info("<<<<:" + string.Join(", ", data));

                string sensorName = data[3];

                if (sensorName == "01")
                {
                    if (data[4] == "00")
                    {
                        ViewModel.HallStatus1.Update("NG", MyBrushes.FAIL);

                    }
                    else
                    {
                        ViewModel.HallStatus1.Update("OK", MyBrushes.PASS);

                    }
                }

                if (sensorName == "02")
                {
                    if (data[4] == "00")
                    {

                        ViewModel.HallStatus2.Update("NG", MyBrushes.FAIL);
                    }
                    else
                    {

                        ViewModel.HallStatus2.Update("OK", MyBrushes.PASS);
                    }
                }

                if (sensorName == "03")
                {
                    if (data[4] == "00")
                    {
                        ViewModel.HallStatus1.Update("NG", MyBrushes.FAIL);
                        ViewModel.HallStatus2.Update("NG", MyBrushes.FAIL);
                        this.ViewModel.TestInfo.HallResult = TestResultState.Fail;
                    }
                    else
                    {
                        ViewModel.HallStatus1.Update("OK", MyBrushes.PASS);
                        ViewModel.HallStatus2.Update("OK", MyBrushes.PASS);

                        this.ViewModel.TestInfo.HallResult = TestResultState.Pass;

                        this.HallSet();
                    }
                    
                }
            }
        }

        private void Instance_OnConnectedChanged(DeviceBase sender, bool isConnect)
        {
            UpdateStartButtonState();
        }
        #endregion

        #region USB
        private void InitUSBDevice()
        {
            USBHelper.Instance.OnMyConnectedChanged += Instansce_OnMyConnectedChanged;
            USBHelper.Instance.OnMyDataReceivedChanged += Instansce_OnMyDataReceivedChanged;
            USBHelper.Instance.Connect();
        }

        private void Instansce_OnMyDataReceivedChanged(object sender, HidReveivedData e)
        {
            byte[] data = e.Data;

            if (ViewModel.TestInfo.IsTesting)
            {
                LogHelper.Info("USB Rec <<<<:" + string.Join(", ", data));

                string sensorName = data[3].ToString("x2");
                string stateName = data[4].ToString("x2");

                if (sensorName == "01")
                {
                    if (stateName == "00")
                    {
                        ViewModel.HallStatus1.Update("NG", MyBrushes.FAIL);

                    }
                    else
                    {
                        ViewModel.HallStatus1.Update("OK", MyBrushes.PASS);

                    }
                }

                if (sensorName == "02")
                {
                    if (stateName == "00")
                    {

                        ViewModel.HallStatus2.Update("NG", MyBrushes.FAIL);
                    }
                    else
                    {

                        ViewModel.HallStatus2.Update("OK", MyBrushes.PASS);
                    }
                }

                if (sensorName == "03")
                {
                    if (stateName == "00")
                    {
                        ViewModel.HallStatus1.Update("NG", MyBrushes.FAIL);
                        ViewModel.HallStatus2.Update("NG", MyBrushes.FAIL);
                        this.ViewModel.TestInfo.HallResult = TestResultState.Fail;
                    }
                    else
                    {
                        ViewModel.HallStatus1.Update("OK", MyBrushes.PASS);
                        ViewModel.HallStatus2.Update("OK", MyBrushes.PASS);

                        this.ViewModel.TestInfo.HallResult = TestResultState.Pass;

                        this.HallSet();
                    }

                }
            }
        }

        private void Instansce_OnMyConnectedChanged(bool isConnect)
        {
            UpdateStartButtonState();
        }

        #endregion

        #region [开始测试]
        private void StartTest()
        {
            if (!ViewModel.TestInfo.EnabledStartButton)
            {
                return;
            }

            //在这里判断USB\COM等设备是否连接


            //判断是否为工程师模式，否则必须输入SN
            if (!ViewModel.EngineerMode)
            {
                string promptText = string.Empty;
                this.ThreadSafe(() =>
                {
                    promptText = this.txtBarcode.PromptText;
                }, false);
                if (string.IsNullOrWhiteSpace(ViewModel.TestInfo.Barcode) || ViewModel.TestInfo.Barcode == promptText)
                {
                    this.ShowDialog("Please input SN Barcode！", App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.Please);
                    this.ThreadSafe(() =>
                    {
                        this.txtBarcode.Focus();
                    }, false);
                    return;
                }
            }
            this.rtxtTestData.Document.Blocks.Clear();

            AppendTestData("开始测试", MyBrushes.Yellow);

            ViewModel.HallStatus1.Update("Testing", MyBrushes.TESTING);
            ViewModel.HallStatus2.Update("Testing", MyBrushes.TESTING);
            //测试开始，更新界面显示
            ViewModel.TestInfo.TestStart();

            //更新状态栏显示
            ViewModel.Status.Update("Testing...", MyBrushes.RichYellow);

            //显示测试中效果UI
            this.Loading.Show("Testing...");

            //在这里重置USB\COM等设备是否连接
            //RelayBoardHelper.Reset();

            Task.Factory.StartNew(() =>
            {
                this.RecordRunLog("请进行Hall测试");

                this.RecordRunLog(string.Format("等待{0}s", TestConfig.Instance.HallTestDelay));
                //在这里执行测试功能
                HallWait(TestConfig.Instance.HallTestDelay);

                this.RecordRunLog("Hall测试结束");

                ViewModel.TestInfo.IsTesting = false;

                //ViewModel.TestInfo.HallResult = TestResultState.Pass;
                if (TestConfig.Instance.ElanTestEnabled)//是否Elan测试
                {
                    if (ViewModel.TestInfo.HallResult == TestResultState.Pass)
                    {
                        AppendTestData("Hall 测试 OK", MyBrushes.Green);

                        RunElanSoftware();

                        ElanWait(TestConfig.Instance.ElanTestDelay);

                    }
                    else
                    {
                        AppendTestData("Hall 测试失败,测试结束", MyBrushes.FAIL);
                    }
                }

            }).ContinueWith(task =>
            {
                this.Loading.Hide();

                FinishTest(false);
            });
        }
        #endregion

        #region [停止测试]
        private void StopTest()
        {
            this.Loading.Show("Stopping...");

            this.FinishTest(true);
        }
        #endregion

        #region [完成测试]
        /// <summary>
        /// 完成测试
        /// </summary>
        /// <param name="isStoped">表示是否手动停止测试</param>
        private void FinishTest(bool isStoped)
        {
            bool IsSuccess = false;

            if (TestConfig.Instance.ElanTestEnabled)
            {
                if (ViewModel.TestInfo.HallResult == TestResultState.Pass && ViewModel.TestInfo.ElanResult == TestResultState.Pass)
                {
                    IsSuccess = true;
                }
            }
            else
            {
                if (ViewModel.TestInfo.HallResult == TestResultState.Pass)
                {
                    IsSuccess = true;
                }
            }

            //获取测试结果状态
            TestResultState result = isStoped ? TestResultState.Stop : IsSuccess ? TestResultState.Pass : TestResultState.Fail;

            ViewModel.TestInfo.TestEnd(result);

            if (isStoped)
            {
                ViewModel.Status.Update("Test Stopped.", MyBrushes.Yellow);
            }
            else
            {
                ViewModel.Status.Update("Test Finished", MyBrushes.Green);

                WriteTestLog(result);
            }

            //在这里重置USB\COM等设备是否连接
            //RelayBoardHelper.Reset();

            this.ThreadSafe(() =>
            {
                this.txtBarcode.Focus();
                this.txtBarcode.SelectAll();
            }, false);

            this.Loading.Hide();

        }
        #endregion

        #region 测试Log记录

        private void WriteTestLog(TestResultState result)
        {
            try
            {
                #region CSV Combine Define
                string collectHeader = string.Format("SerialNumber,overallResult,startTime,endTime,testTime");

                string collectData = string.Format("{0},{1},{2},{3},{4}",
                                         ViewModel.TestInfo.Barcode,
                                         result.ToString().ToUpper(),
                                         ViewModel.TestInfo.TestTimer.StartTime.ToString("yyyy/MM/dd HH:mm:ss"),
                                         ViewModel.TestInfo.TestTimer.EndTime.ToString("yyyy/MM/dd HH:mm:ss"),
                                         ViewModel.TestInfo.TestTimer.TestTime);
                #endregion

                if (!string.IsNullOrWhiteSpace(ViewModel.TestInfo.Barcode))
                {
                    string saveDir = string.Format(@"{0}TestLog\{1}\{2}\{3}\", this.GetBaseDirectory(), ViewModel.TestConfig.Project, DateTime.Now.ToString("yyyy-MM-dd"), result.ToString().ToUpper());
                    if (!System.IO.Directory.Exists(saveDir))
                    {
                        System.IO.Directory.CreateDirectory(saveDir);
                    }

                    string logFileName = saveDir + string.Format(@"{0}_{1}_{2}_{3}_{4}.csv", result.ToString().ToUpper(), ViewModel.TestInfo.Barcode, ViewModel.TestConfig.Project, ViewModel.TestConfig.Station, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

                    string csvFileName = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(saveDir)) + string.Format(@"\Combine-{0}-{1}-{2}.csv", ViewModel.TestConfig.Project, ViewModel.TestConfig.Station, DateTime.Now.ToString("yyyy-MM-dd"));

                    bool isExists = System.IO.File.Exists(csvFileName);
                    StringBuilder sbCsv = new StringBuilder();
                    if (!isExists)
                    {
                        sbCsv.AppendLine(string.Format("{0} V{1}", this.GetAssemblyName(), this.GetVersion()));
                        sbCsv.AppendLine("Project, " + ViewModel.TestConfig.Project);
                        sbCsv.AppendLine("Station, " + ViewModel.TestConfig.Station);
                        sbCsv.AppendLine(collectHeader);
                    }
                    sbCsv.AppendLine(collectData);

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(logFileName, false, Encoding.UTF8))
                    {
                        StringBuilder sbLog = new StringBuilder();
                        sbLog.AppendLine(string.Format("{0} V{1}", this.GetAssemblyName(), this.GetVersion()));
                        sbLog.AppendLine("Project, " + ViewModel.TestConfig.Project);
                        sbLog.AppendLine("Station, " + ViewModel.TestConfig.Station);
                        sbLog.AppendLine(collectHeader);
                        sbLog.AppendLine(collectData);
                        sw.Write(sbLog.ToString());
                        sw.Close();
                    }

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(csvFileName, true, Encoding.UTF8))
                    {
                        sw.Write(sbCsv.ToString());
                        sw.Close();
                    }

                    if (File.Exists(logFileName))
                    {
                        string zipDir = string.Format(@"{0}ZipTestLog\{1}\{2}\{3}\", this.GetBaseDirectory(), ViewModel.TestConfig.Project, DateTime.Now.ToString("yyyy-MM-dd"), result.ToString().ToUpper());

                        if (!System.IO.Directory.Exists(zipDir))
                        {
                            System.IO.Directory.CreateDirectory(zipDir);
                        }

                        string ZipFile = zipDir + string.Format(@"{0}_{1}_{2}_{3}_{4}.zip", result.ToString().ToUpper(), ViewModel.TestInfo.Barcode, ViewModel.TestConfig.Project, ViewModel.TestConfig.Station, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

                        List<string> zipFiles = new List<string>();

                        zipFiles.Add(logFileName);
                        //AppendTestData(string.Format("添加Hall测试文件：{0}", logFileName), MyBrushes.Yellow);

                        if(ViewModel.TestInfo.ElanTestLog != null && ViewModel.TestInfo.ElanTestLog != "")
                        {
                            if(File.Exists(ViewModel.TestInfo.ElanTestLog))
                            {
                                zipFiles.Add(ViewModel.TestInfo.ElanTestLog);
                                //AppendTestData(string.Format("添加Elan测试文件：{0}", ViewModel.TestInfo.ElanTestLog), MyBrushes.Yellow);

                            }
                        }
                        AppendTestData("压缩中...", MyBrushes.Yellow);

                        if (Bandit.Zip.ZipHelper.ZipFiles(zipFiles.ToArray(), ZipFile))
                        {

                            AppendTestData(string.Format("压缩成功,路径：{0}", ZipFile), MyBrushes.Green);
                        }
                        else
                        {
                            AppendTestData(string.Format("压缩失败"), MyBrushes.Red);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "WriteTestLog");
            }
        }

        #endregion

        #region 追加测试信息
        private void RecordRunLog(string data, MyBrushes brush = MyBrushes.Yellow)
        {
            AppendTestData(data, brush);
        }

        private Block AppendTestData(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, statusBrush);

                this.rtxtTestData.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = AppendTestData(data, statusBrush);
                });
            }

            return block;
        }

        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }
        #endregion


        #region Elan软体
        private string Elan_Title;

        private FileSystemWatcher _Elan_LogWatcher;

        private System.Diagnostics.Process _Elan_SoftwareProcess;

        TestResultState _Elan_TestResultState = TestResultState.Idle;

        public delegate bool EnumWindowsProc(IntPtr hWnd, string lParam);
        public static EnumWindowsProc callBackEnumChildWindows = new EnumWindowsProc(EnumChildWindowsCallBack);

        public static bool EnumChildWindowsCallBack(IntPtr hwnd, string lParam)
        {
            StringBuilder title = new StringBuilder(250);
            WinAPIManager.GetWindowText(hwnd, title, 250);
            LogHelper.Info(title);
            if (title.ToString().ToUpper().Contains("START"))
            {
                WinAPIManager.SendMessage(hwnd, 245, 0, null);
            }
            //if (title.ToString().ToUpper().Contains("停止测试"))
            //{
            //    WinAPIManager.SendMessage(hwnd, WM_LBUTTONDOWN, 0, null);
            //    WinAPIManager.SendMessage(hwnd, WM_LBUTTONDOWN, 0, null);
            //    WinAPIManager.SendMessage(hwnd, WM_LBUTTONUP, 0, null);
            //    WinAPIManager.SendMessage(hwnd, WM_LBUTTONUP, 0, null);
            //}
            return true;
            //StringBuilder sb = new StringBuilder(256);
            //StringBuilder title = new StringBuilder(250);
            //WinAPIManager.GetWindowText(hwnd, title, 250);
            ////Rectangle rct = new Rectangle();
            //WinAPIManager.GetClassName(hwnd, sb, 256);
            ////WinAPIManager.GetWindowRect(hwnd, out rct);
            //if (sb.ToString().Contains("WindowsForms10.EDIT.app") && title.ToString().Equals(""))
            //{
            //    WinAPIManager.SendMessage(hwnd, 12, 0, lParam);
            //    //WinAPIManager.SendMessage(hwnd, 0x104, 0X0D, 0);
            //    return false;
            //}
            //return true;
        }
        //运行Elan测试软体
        private void RunElanSoftware()
        {
            this.RecordRunLog(string.Format("打开Elan软件..."));

            //bool isFirst = false;

            #region 启动测试软件
            try
            {
                if (_Elan_SoftwareProcess.IsNull())
                {
                    string fileName = this.ViewModel.TestConfig.Elan_Software;
                    if (File.Exists(fileName))
                    {
                        string arguments = string.Empty;

                        _Elan_SoftwareProcess = new System.Diagnostics.Process();
                        _Elan_SoftwareProcess.StartInfo.FileName = fileName;
                        _Elan_SoftwareProcess.StartInfo.Arguments = arguments;
                        _Elan_SoftwareProcess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(fileName);
                        _Elan_SoftwareProcess.EnableRaisingEvents = true;
                        _Elan_SoftwareProcess.Exited += delegate
                        {
                            _Elan_SoftwareProcess = null;
                            Elan_TestEnded(TestResultState.Idle);
                        };
                        _Elan_SoftwareProcess.Start();
                        //isFirst = true;
                        Thread.Sleep(3000);
                        Elan_Title = _Elan_SoftwareProcess.MainWindowTitle;

                    }
                    else
                    {
                        this.ShowDialog("测试软体不存在！", App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.WuYu);
                        return;
                    }
                }

                WinAPIManager.ShowWindow(_Elan_SoftwareProcess.MainWindowHandle, 1);

                Bandit.Helpers.LogHelper.Info(string.Format("# Run Test Software Done! # "));

                ViewModel.Status.Update("启动测试软件...", MyBrushes.White);

                IntPtr ElanPtr = WinAPIManager.FindWindow(null, _Elan_SoftwareProcess.MainWindowTitle);

                WinAPIManager.EnumChildWindows(ElanPtr, callBackEnumChildWindows, this.ViewModel.TestInfo.Barcode);//将barcode写入textbox  

            }
            catch (Exception ex)
            {
                _Elan_SoftwareProcess = null;
                LogHelper.Error(ex, "MainWindow.Start", true);
                this.ShowDialog("测试软体启动失败 ：" + Environment.NewLine + ex.GetMessage(), App.GetString("Error"), MessageBoxButton.OK, Bandit.UI.DialogIcon.Shame);
                return;
            }

            #endregion

            if (StartElan_LogWatcher())
            {
                this.RecordRunLog(string.Format("监视Elan软件测试结果..."));

                this.RecordRunLog(string.Format("等待{0}s",TestConfig.Instance.ElanTestDelay));

                this._Elan_SoftwareProcess.MainWindowHandle.ShowWindow();

            }
            else
            {
                this.ShowDialog(App.GetString("TestSoftwareLogDirEmpty"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.WuYu);
            }
        }

        //this.ElanWait(PLCConfig.Instance.BUITestDelay);
        //关联软体
        private void LinkSoftware()
        {
            #region 关联运行中的BUI/CMI测试软件
            var processList = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(this.ViewModel.TestConfig.Elan_Software));
            if (processList.Length == 1)
            {
                _Elan_SoftwareProcess = processList[0];
                _Elan_SoftwareProcess.EnableRaisingEvents = true;
                _Elan_SoftwareProcess.Exited += delegate
                {
                    _Elan_SoftwareProcess = null;
                    Elan_TestEnded(TestResultState.Idle);
                };
            }
            else
            {
                foreach (var process in processList)
                {
                    process.Kill();
                }
            }
            #endregion

        }

        private void Elan_TestEnded(TestResultState testResultState, string logFileFullPath = null)
        {
            LogHelper.Info(string.Format("# --------------- Elan_TestEnded : {0} - {1} --------------- #", ViewModel.TestInfo.Barcode, testResultState));

            if (testResultState == TestResultState.Idle)
            {
                this.RecordRunLog(string.Format("Elan测试软体已关闭."));
            }
            else
            {
                this.RecordRunLog(string.Format("Elan测试软体测试完成. 结果 : {0}", testResultState), testResultState == TestResultState.Pass ? MyBrushes.PASS : MyBrushes.FAIL);
            }


            Elan_StopLogWatcher();

            ViewModel.TestInfo.ElanResult= testResultState;

            ViewModel.TestInfo.ElanTestLog = logFileFullPath;

#region 显示窗体
            this.ThreadSafe((Action)delegate
            {
                if (this.Visibility != System.Windows.Visibility.Visible)
                {
                    this.Show(Bandit.UI.Animation.Scale | Bandit.UI.Animation.Opacity, 0.3, delegate
                    {
                        this.Handle.ShowWindow();

                        this.txtBarcode.Focus();
                    });
                }
                else
                {
                    this.Handle.ShowWindow();

                    this.txtBarcode.Focus();
                }

                ViewModel.UpdateStatus("TestComplete");

                this.txtBarcode.Focus();
                this.txtBarcode.SelectAll();

                this.Handle.ShowWindow();

                WinAPIManager.ShowWindow(_Elan_SoftwareProcess.MainWindowHandle, 0);

            });
#endregion

            this.ElanSet();
        }

        private void InitializeLogWathcer()
        {
            _Elan_LogWatcher = new FileSystemWatcher();

            _Elan_LogWatcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.FileName;

            //_BUI_CMI_LogWatcher.Created += BUI_CMI_FileSystemWatcher_Created;

            _Elan_LogWatcher.Changed += Elan_FileSystemWatcher_Created;

            _Elan_LogWatcher.Error += (sender, e) =>
            {
                LogHelper.Error(e.GetException(), "Elan_FileSystemWatcher.Error", true);
            };

        }
        private bool StartElan_LogWatcher()
        {
            string path = this.ViewModel.TestConfig.Elan_LogPath;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            _Elan_LogWatcher.Path = path;
            _Elan_LogWatcher.Filter = "*.csv";

            _Elan_LogWatcher.IncludeSubdirectories = true;
            _Elan_LogWatcher.EnableRaisingEvents = true;

            ViewModel.UpdateStatus(App.GetString("StartWatcher"));

            Bandit.Helpers.LogHelper.Info(string.Format("# Elan Log Watcher Running... {0} # ", _Elan_LogWatcher.Path));

            return true;
        }

        private void Elan_StopLogWatcher()
        {
            Bandit.Helpers.LogHelper.Info(string.Format("# Elan Stop Log Watcher. # "));

            _Elan_LogWatcher.EnableRaisingEvents = false;

        }

        private void Elan_FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {

            //考虑到可能存在数据未写入完毕文件被锁的情况，先休眠500ms
            System.Threading.Thread.Sleep(200);

            lock (this)
            {
                LogHelper.Info(string.Format("# Elan Watcher Result {0} -> {1} #", e.ChangeType, e.FullPath));

                // 如果监视到文件名存在忽略标志就忽略
                if (e.Name.Contains("ALL"))
                {
                    LogHelper.Info(string.Format("* Return - Ignore {0} *", e.Name.ToUpper()));
                    return;
                }

                // 过滤重复触发
                //if (_PreviousSN.Equals(ViewModel.TestInfo.Barcode) &&
                //    _PreviousPath.Equals(e.FullPath) &&
                //    (DateTime.Now - _PreviousTime) <= TimeSpan.FromSeconds(3))
                //{
                //    LogHelper.Info(string.Format("* Return - Repeat {0} *", e.FullPath));
                //    return;
                //}

                //_PreviousSN = ViewModel.TestInfo.Barcode;
                //_PreviousPath = e.FullPath;
                //_PreviousTime = DateTime.Now;
            }

            switch (e.ChangeType)
            {
                case WatcherChangeTypes.Created:
                case WatcherChangeTypes.Changed:
                    TestResultState testResultState = TestResultState.Idle;
                    string uploadFile = e.FullPath;

                    if (uploadFile.ToUpper().Contains("PASS"))
                    {
                        testResultState = TestResultState.Pass;
                    }
                    else if (uploadFile.ToUpper().Contains("FAIL"))
                    {
                        testResultState = TestResultState.Fail;
                    }

                    if (testResultState == TestResultState.Idle)
                    {
                        LogHelper.Info(string.Format("* ERR - Unknown Result - {0} *", e.FullPath));
                    }
                    else
                    {
                        this.Elan_TestEnded(testResultState, uploadFile);
                    }
                    break;
                default:
                    break;
            }
           
        }


        #region Elan Autoset

        private AutoResetEvent _ElanAutoEvent = new AutoResetEvent(false);
        private void ElanSet()
        {
            this._ElanAutoEvent.Set();
        }

        private void ElanWait(int seconds)
        {
            this._ElanAutoEvent.Reset();
            this._ElanAutoEvent.WaitOne(TimeSpan.FromSeconds(seconds));
        }

        #endregion

        #endregion
    }
}
